import { useState, useRef } from 'react'
// React 中处理表单的组件
import { useFormik } from 'formik'
// 路由组件
import { useHistory } from 'react-router-dom'
// 表单验证的包
import * as Yup from 'yup'
//  CSS 的模块化，自动生成类名，className={styles.类名}
import styles from './index.module.scss'
// import axios from 'axios'
// 轻提示
import { Toast } from 'antd-mobile'
import { http, setToken } from '@/utils'
import Input from '@/components/Input'
import NavBar from '@/components/NavBar'
// let timerId=-1
// history历史包是react路由底层主要依赖
const Login = () => {
  const history=useHistory()
  //倒计时
  const [time, setTime] = useState(0)
  // 定时器 id
  const timerIdRef = useRef(-1)
  // console.log(timerIdRef);
  //存储手机号码对应文本框DOM元素
  // DOM元素获取不到时默认值为null
  const mobileRef = useRef(null)
  // 一个专门用来在 React 中处理表单的组件：formik
  const formik = useFormik({
    //   initialValues初始值
    initialValues: {
      mobile: '',
      code: '',
    },
    // Yup.object() 表示要对对象进行验证，参数是一个对象，表示可以对每个属性进行单独的验证
    // matches 过滤条件
    // validationSchema 验证模式
    validationSchema: Yup.object({
      mobile: Yup.string()
        // required() 的参数就是：验证失败时的错误信息
        .required('手机号为必填项')
        .matches(/^1[3-9]\d{9}$/, '手机号码格式不正确'),
      code: Yup.string()
        .required('验证码为必填项')
        .matches(/^\d{6}$/, '验证码不正确'),
    }),
    // 表单提交
    onSubmit: async values => {
      try {
        const res = await http.post('/authorizations', values)
        if (res.data.message.toLowerCase() === 'ok') {
          Toast.info('登录成功', 1, () => {
            // 清理定时器
            clearInterval(timerIdRef.current)
            history.push('/home')
            setToken(res.data.data)
          })
        }
      } catch (e) {
        // Toast.info(提示信息, 时长, 关闭回调)
        Toast.info(e.response.data.message, 2)
      }
    },
  })
  // 发送请求获取验证码
  const getCode = async () => {
    if (time > 0) return
    const { mobile } = formik.values
    // console.log(mobile)
    // 使用正则来校验手机号码
    if (!/^1[3-9]\d{9}$/.test(mobile)) {
      mobileRef.current.focus()

      return Toast.info('请输入手机号', 1)
    }

    setTime(4)
    clearInterval(timerIdRef.current)
    //定时器
    timerIdRef.current = setInterval(() => {
      setTime(time => {
        if (time === 1) {
          clearInterval(timerIdRef.current)
        }

        return time-1
      })
      // console.log(time);
    }, 1000)
    // 手机号码验证成功：
    try {
      await http.get(`/sms/codes/${mobile}`)
    } catch (e) {}
  }
  // handleSubmit 处理表单的提交事件
  const {
    handleSubmit,
    handleChange,
    handleBlur,
    values: { mobile, code },
    touched,
    errors,
    isValid,
  } = formik

  //   const getCode =async mobile => {
  //     if (!/^1[3-9]\d{9}$/.test(mobile)) return
  //     try{
  //        await axios.get(`http://geek.itheima.net/v1_0/sms/codes/${mobile}`)
  //     }catch(e){}
  //   }

  // Object.keys(对象)用来获取对象中所有键，返回一个数组放这些键
  const isFirst = Object.keys(touched).length === 0
  return (
    <div className={styles.root}>
      <NavBar
        onClick={() => {
          history.go(-1)
        }}
      />
      <h1 className="title">账号登录</h1>
      <div className="login-wrap">
        <form onSubmit={handleSubmit}>
          <div className="form-item">
            <Input
              type="text"
              placeholder="请输入手机号"
              name="mobile"
              value={mobile}
              onChange={handleChange}
              onBlur={handleBlur}
              dom={mobileRef}
              maxLength={11}
            />

            <div className="error">
              {touched.mobile && errors.mobile ? <div>{errors.mobile}</div> : null}
            </div>
          </div>
          <div className="form-item">
            <Input
              extra={time <= 0 ? ' 发送验证码' : `${time}s`}
              onExtraClick={getCode}
              name="code"
              type="text"
              placeholder="请输入验证码"
              value={code}
              onChange={handleChange}
              onBlur={handleBlur}
            />
            {/* <span className="code-text" onClick={getCode}>
              {time <= 0 ? ' 发送验证码' : `${time}s`}
            </span> */}
            <div className="error">
              {touched.code && errors.code ? <div>{errors.code}</div> : null}
            </div>
          </div>
          <div className="form-item">
            <button
              type="submit"
              disabled={isFirst || !isValid}
              className={isFirst ? '' : isValid ? 'active' : ''}
            >
              登录
            </button>
          </div>
        </form>
      </div>
    </div>
  )
}
export default Login
